﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSVideoUploader.Util
{
    /// <summary>
    /// 数据工具类
    /// 负责数据转换
    /// </summary>
    class DataUtility
    {
        /// <summary>
        /// 将十六进制字符串，转换为字节流
        /// </summary>
        /// <param name="hex">十六进制字符串</param>
        /// <returns></returns>
        public static byte[] Hex2Bytes(string hex)
        {
            // 补足为偶数长度
            if (hex.Length % 2 != 0)
            {
                hex = "0" + hex;
            }

            // 初始化缓冲区
            int len = hex.Length / 2;
            byte[] bytes = new byte[len];
            for (int i = 0; i < len; i++)
            {
                string hexByte = hex.Substring(i * 2, 2);
                bytes[i] = Convert.ToByte(hexByte, 16);
            }

            return bytes;
        }

        /// <summary>
        /// 将字节流转换为十六进制字符串
        /// </summary>
        /// <param name="bytes">字节流</param>
        /// <returns></returns>
        public static String Bytes2Hex(byte[] bytes)
        {
            StringBuilder buf = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                string byteStr = Convert.ToString(bytes[i], 16);
                if (byteStr.Length != 2)
                {
                    buf.Append("0");
                }
                buf.Append(byteStr);
            }
            return buf.ToString();
        }
    }
}
